<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Http\Requests\Admin\BaseRequest;
use App\Models\Admin\Goods;
use App\Models\Admin\GoodsCategory;
use App\Models\Admin\GoodsDatum;
use App\Models\Admin\GoodsDetail;
use App\Models\Admin\GoodsImage;
use App\Models\Admin\GoodsNonstandard;
use App\Models\Admin\GoodsSpu;
use App\Models\Admin\GoodsStandard;
use App\Models\Admin\GoodsStandardName;
use App\Models\Admin\GoodsStandardSpu;
use Auth,DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class GoodsStandardController extends AdminController
{
    use AdminTrait;

    protected $model;
    protected $unique_id = '';
    protected $type_brand=4;
    public function __construct(GoodsStandard $model)
    {
        parent::__construct();
        $this->model = $model;
    }
    /**
     * 定义验证规则
     * @var []
     */
    protected $validate_rule = [
        'category_id' => 'required|integer|min:1|exists:goods_category,id',
        'pid'        => 'required|integer|min:1|exists:goods_category,id',
        'pinyin'      => 'nullable|alpha',
    ];

    /**
     * 定特殊的验证规则
     */
    protected function rules()
    {
        return [
            'name'     => [
                'required',
                Rule::unique('goods_standard')->ignore($this->unique_id),
                Rule::unique('goods_nonstandard'),
            ],
//            'standard_code' => [
//                'filled',
//                Rule::unique('goods_standard')->ignore($this->unique_id),
//            ],
        ];
    }

    protected $err_msg = [
        'name.required'         => '名称不能为空',
        'name.unique'           => '该名称已存在',
        'standard_code.unique'       => '商品编码已存在',
        'category_id.min'            => '请选择商品的二级分类',
        'pinyin.alpha'           => '关键词必须全部为字母',
    ];

    protected $statusList = [
        0 => '下架',
        1 => '上架',
    ];

    protected $standardList = [
        0 => '非标品',
        1 => '标品',
    ];

    protected $recommendList = [
        0 => '否',
        1 => '是',
    ];

    protected function search($request)
    {
        $select = $this->model->with(['spu'=>function($query){
            $query->with(['spuName','spuUnit']);
        },'category','category_p','standardName']);

        $pid = $request->query('pid');
        $category_id   = $request->query('category_id');
        if ($category_id) {
            $select = $select->where('category_id',$category_id);
        } else if ($pid) {
            $select = $select->where('pid',$pid);
        }
        $is_standard = $request->query('is_standard');
        if(!is_null($is_standard))
        {
            $select = $select->where('is_standard',$is_standard);
        }
        if($brand = $request->query('brand'))
        {
            $select = $select->where('brand',$brand);
        }
        if ($name = $request->query('name')){
            $select = $select->where(function ($query)use ($name){
                $query->orWhere('name','like',"%$name%")->orWhere('pinyin','like',"%$name%")->orWhere('standard_code','like',"%$name%");
            });
        }
        return $select;
    }

    protected function beforeIndex()
    {
        $categoryList = GoodsCategory::getCategorys();
        //返回品牌数据
        $brand=GoodsDatum::getDatum($this->type_brand);

        return ['categoryList'=>$categoryList,'brand_list'=>$brand];
    }

    protected function setRequestField($arr,$type=false)
    {
        //过滤字段
        if(isset($arr['_token'])) unset($arr['_token']);
        if (isset($arr['list'])) unset($arr['list']);
        if (isset($arr['purchase_relation'])) unset($arr['purchase_relation']);
        if (isset($arr['sign'])) unset($arr['sign']);
        if (isset($arr['timeStamp'])) unset($arr['timeStamp']);
        if (isset($arr['name_list'])) unset($arr['name_list']);
        if(isset($arr['standard_code'])) unset($arr['standard_code']);
        return $arr;
    }

    public function createSpu($request)
    {
        $category_id=isset($request['category_id'])?$request['category_id']:0;
        $code_category=GoodsCategory::where('id',$category_id)->value('code');
        if(!$code_category) return false;
        $spu_max=GoodsStandard::where('category_id',$category_id)->max('standard_code');
        if(is_null($spu_max))
        {
            $spu=$code_category.'001';
        }
        else
        {
            $spu=(string)($spu_max+1);
            $spu=strlen($spu)==6?'0'.$spu:$spu;
        }
        return $spu;
    }

    public function createSku($info)
    {
        $standard_id=$info->id;
        $spu=$info->standard_code;
        $sku_max=GoodsStandardSpu::where('standard_goods_id',$standard_id)->max('standard_spu_code');
        if(is_null($sku_max))
        {
            $sku='C'.$spu.'10';
        }
        else
        {
            $sku_max_num=substr($sku_max,1);
            $sku_num=(string)($sku_max_num+1);
            $sku_num=strlen($sku_num)==8?'0'.$sku_num:$sku_num;
            $sku='C'.$sku_num;
        }
        return $sku;
    }

    public function add(BaseRequest $request)
    {
        isset($this->unique_id) && $this->unique_id = 0;

        if(true !== $msg = $this->validate_form($request)){
            //验证未通过
            return response()->json(['errcode'=>'40012','errmsg'=>$msg]);
        }

        //去除数组
        $data = $this->setRequestField($request->all());

        //生成spu
        $spu=$this->createSpu($request->all());
        if($spu===false)
        {
            return response()->json(['errcode'=>'-1','errmsg'=>'商品分类不存在']);
        }
        $data['standard_code']=$spu;

        DB::beginTransaction();
        try{
            //执行添加操作
            $result = $this->model->create($data);
            //后置操作
            if (method_exists($this, 'afterData')) {
                $this->afterData($result,$request->all());
            }
            if (method_exists($this->model,'addLog')){
                $this->model->addLog($result,[],1,'');
            }
            //Log::info($result);
            DB::commit();
            return response()->json(['errcode'=>0,'errmsg'=>'ok']);
        }catch (\Exception $e){
            report($e);
            DB::rollBack();
            if ($e->getMessage() == '40065'){
                return $this->error(['40065','sku编码必须唯一']);
            }else{
                return response()->json(['errcode'=>40006,'errmsg'=>'添加失败']);
            }
        }
    }

    public function edit(BaseRequest $request)
    {

        isset($this->unique_id) && $this->unique_id = $request->id;

        if(true !== $msg = $this->validate_form($request)){
            //验证未通过
            return response()->json(['errcode'=>'40012','errmsg'=>$msg]);
        }

        //获取模型
        $info = $this->model->findOrFail($request->id);
        //判断分类是否有更改
        $flage=false;
        if($request->category_id!=$info->category_id || $request->pid!=$info->pid)
        {
            if($info->tally>0)
            {
                return $this->error(['-1','商品已被导入过，不能修改分类']);
            }
            $flage=true;
            //生成新的spu
            $spu_new=$this->createSpu($request->all());
            $info->category_id=$request->category_id;
            $info->pid=$request->pid;
            $info->standard_code=$spu_new;
        }

        DB::beginTransaction();
        try{
            if($flage)
            {
                $sku_list=GoodsStandardSpu::where('standard_goods_id',$request->id)->get()->toArray();
                foreach ($sku_list as $v)
                {
                    $standard_spu_code=$v['standard_spu_code'];
                    $end_2=substr($standard_spu_code,-2);
                    $sku_new='C'.$info->standard_code.$end_2;
                    GoodsStandardSpu::where('id',$v['id'])->update(['standard_spu_code'=>$sku_new]);
                }
            }
            //赋值
            foreach ($this->setRequestField($request->all(),true) as $k=>$v){
                if(!is_array($v)  && !in_array($k,['category_id','pid']) ){
                    $info->$k = $v;
                }
            }
            $perInfo = $info->getOriginal();//获取修改之前的字段
            //执行修改操作
            $info->save();
            $nextInfo = $info->getChanges();//获取修改之后的字段
            //后置操作
            if (method_exists($this, 'afterData')) {
                $this->afterData($info,$request->all());
            }

            if (method_exists($this->model,'addLog')){
                if (!empty($nextInfo)){
                    $this->model->addLog($perInfo,$nextInfo,2,'');
                }
            }

            DB::commit();
            return response()->json(['errcode'=>0,'errmsg'=>'ok']);
        }catch (\Exception $e){
            report($e);
            DB::rollBack();
            if ($e->getMessage() == '40065'){
                return $this->error(['40065','sku编码必须唯一']);
            }else{
                return $e->getMessage();
                return response()->json(['errcode'=>40007,'errmsg'=>'修改失败']);
            }
        }
    }

    protected function afterData($info,$requestData)
    {
        //编辑
        if (isset($requestData['id'])){
            $attr = json_decode($requestData['list'],true);
            foreach ($attr as $k => $v){
                if (isset($v['id']) && $v['id']){
                    $save = GoodsStandardSpu::find($v['id']);
                    foreach ($v as $kk => $vv) {
                        if($kk!='standard_spu_code')
                        {
                            $save->$kk = $vv;
                        }
                    }
                    $save->save();
                }else{
                    $sku=$this->createSku($info);
                    $v['standard_spu_code']=$sku;
                    $v['standard_goods_id'] = $info->id;
                    GoodsStandardSpu::create($v);
                }
            }
            //判断是否要更改用户的商品表
            if(isset($requestData['name']))
            {
                Goods::where('standard_goods_id',$requestData['id'])->update(['name'=>$requestData['name']]);
            }
        }
        //新增
        else{
            if (!empty($requestData['list'])){
                $attr = json_decode($requestData['list'],true);
                foreach ($attr as $k => $v){
                    $sku=$this->createSku($info);
                    $v['standard_goods_id'] = $info->id;
                    $v['standard_spu_code'] = $sku;
                    GoodsStandardSpu::create($v);
                }
            }
        }

        //存储名称
        if (isset($requestData['name_list'])){
            $name_list = explode(',',$requestData['name_list']);
            $name_list=empty($name_list[0])?[]:$name_list;
            GoodsStandardName::addNames($info->id,$name_list);
        }
    }

    private function checkSkuCode($id,$code)
    {
        $flag = GoodsStandardSpu::where('id','!=',$id)
            ->where('standard_spu_code',$code)
            ->count();
        if ($flag){
            return $this->error(['40065','spu编码必须唯一']);
        }
        return [];
    }

    private function checkNameFun($name,$standard_id=0,$name_id=0,$nonstandard_id=0)
    {
        $flag = GoodsStandard::where('id','!=',$standard_id)
            ->where('name',$name)
            ->count();
        if ($flag){
            return $this->error(['60065','名称已存在']);
        }
        $flag = GoodsStandardName::where('id','!=',$name_id)
            ->where('name',$name)
            ->count();
        if ($flag){
            return $this->error(['60065','名称已存在']);
        }
        $flag = GoodsNonstandard::where('id','!=',$nonstandard_id)
            ->where('name',$name)
            ->count();
        if ($flag){
            return $this->error(['60065','名称已存在']);
        }
        return [];
    }
    public function baseData(BaseRequest $request)
    {
        $categoryList = GoodsCategory::getCategorys();

        //返回品牌数据
        $brand=GoodsDatum::getDatum($this->type_brand);
        $unit=GoodsDatum::getDatum(1);
        $tag=GoodsDatum::getDatum(2);
        $attribute=GoodsDatum::getDatum(3);
        return response()->json(['errcode'=>0,'data'=>['category'=>$categoryList,'unit'=>$unit,'tag'=>$tag,'attribute'=>$attribute,'brand'=>$brand],'errmsg'=>"ok"]);
    }

    public function info(BaseRequest $request)
    {
        try {
            $id = $request->id;
            if (!is_numeric($id)){
                return response()->json(['errcode'=>40016,'errmsg'=>'参数错误']);
            }
            $info = $this->model->with(['spu'=>function($query){
                $query->with(['spuName','spuUnit']);
            },'category','category_p','standardName'])->findOrFail($id);

            return response()->json(['errcode'=>0,'data'=>['info'=>$info->toArray()],'errmsg'=>'ok']);
        }catch (\Exception $exception){
            return response()->json(['errcode'=>40009 ,'errmsg'=>'信息不存在']);
        }
    }

    public function checkName(BaseRequest $request)
    {
        $input=$request->all();
        $standard_id=isset($input['standard_id'])?$input['standard_id']:0;
        $name_id=isset($input['name_id'])?$input['name_id']:0;
        $rules=[
            'name'     => [
                'required',
                Rule::unique('goods_standard')->ignore($standard_id),
                Rule::unique('goods_standard_name')->ignore($name_id),
                Rule::unique('goods_nonstandard'),
            ],
            'standard_id'=>'integer',
            'name_id'=>'integer',
        ];
        $validator = Validator::make($input, $rules,$this->err_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        return response()->json(['errcode'=>'0','errmsg'=>'ok']);
    }


}
